<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>文档标题</title>
</head>
<body>
聊天信息：<input id="chat" >
<button id="send" onclick="sendFun()">发送</button>
<button id="close" onclick="closeFun()">关闭</button>
</body>

<script>

var sendFun = function(){
	var msg = document.getElementById("chat").value;
	var sendData = {
		"fromUserId":"1",
		"toUserId":"10",
		"msgType":"2",
		"msg":msg
	}
	socket.send(JSON.stringify(sendData));
}
var closeFun = function(){
	socket.close();
}

var socket;

window.onload=function(){ 
	if(typeof(WebSocket) == "undefined") {
		console.log("您的浏览器不支持WebSocket");
	}else{
		//实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
		socket = new WebSocket("ws://localhost:8080/socket")
		//打开事件
		socket.onopen = function() {
			let sendData = {
				"fromUserId":"1",
				"msgType":"1"
			}
			socket.send(JSON.stringify(sendData));  //发送注册信息
		}
		//获得消息事件
		socket.onmessage = function(msg) {
			console.log("服务端返回数据："+msg.data);
			//发现消息进入
		}
		//关闭事件
		socket.onclose = function() {
			console.log("Socket已关闭");
		}
		//发生了错误事件
		socket.onerror = function() {
			alert("Socket发生了错误");
		}
	}
}


</script>

</html>